--- Day 11: Radioisotope Thermoelectric Generators ---

You come upon a column of four floors that have been entirely sealed off from the rest of the building except for a small dedicated lobby. There are some radiation warnings and a big sign which reads "Radioisotope Testing Facility".

According to the project status board, this facility is currently being used to experiment with Radioisotope Thermoelectric Generators (RTGs, or simply "generators") that are designed to be paired with specially-constructed microchips. Basically, an RTG is a highly radioactive rock that generates electricity through heat.

The experimental RTGs have poor radiation containment, so they're dangerously radioactive. The chips are prototypes and don't have normal radiation shielding, but they do have the ability to generate an elecromagnetic radiation shield when powered. Unfortunately, they can only be powered by their corresponding RTG. An RTG powering a microchip is still dangerous to other microchips.

In other words, if a chip is ever left in the same area as another RTG, and it's not connected to its own RTG, the chip will be fried. Therefore, it is assumed that you will follow procedure and keep chips connected to their corresponding RTG when they're in the same room, and away from other RTGs otherwise.

These microchips sound very interesting and useful to your current activities, and you'd like to try to retrieve them. The fourth floor of the facility has an assembling machine which can make a self-contained, shielded computer for you to take with you - that is, if you can bring it all of the RTGs and microchips.

Within the radiation-shielded part of the facility (in which it's safe to have these pre-assembly RTGs), there is an elevator that can move between the four floors. Its capacity rating means it can carry at most yourself and two RTGs or microchips in any combination. (They're rigged to some heavy diagnostic equipment - the assembling machine will detach it for you.) As a security measure, the elevator will only function if it contains at least one RTG or microchip. The elevator always stops on each floor to recharge, and this takes long enough that the items within it and the items on that floor can irradiate each other. (You can prevent this if a Microchip and its Generator end up on the same floor in this way, as they can be connected while the elevator is recharging.)

You make some notes of the locations of each component of interest (your puzzle input). Before you don a hazmat suit and start moving things around, you'd like to have an idea of what you need to do.

When you enter the containment area, you and the elevator will start on the first floor.

For example, suppose the isolated area has the following arrangement:

The first floor contains a hydrogen-compatible microchip and a lithium-compatible microchip.
The second floor contains a hydrogen generator.
The third floor contains a lithium generator.
The fourth floor contains nothing relevant.
As a diagram (F# for a Floor number, E for Elevator, H for Hydrogen, L for Lithium, M for Microchip, and G for Generator), the initial state looks like this:

F4 .  .  .  .  .  
F3 .  .  .  LG .  
F2 .  HG .  .  .  
F1 E  .  HM .  LM 
Then, to get everything up to the assembling machine on the fourth floor, the following steps could be taken:

Bring the Hydrogen-compatible Microchip to the second floor, which is safe because it can get power from the Hydrogen Generator:

F4 .  .  .  .  .  
F3 .  .  .  LG .  
F2 E  HG HM .  .  
F1 .  .  .  .  LM 
Bring both Hydrogen-related items to the third floor, which is safe because the Hydrogen-compatible microchip is getting power from its generator:

F4 .  .  .  .  .  
F3 E  HG HM LG .  
F2 .  .  .  .  .  
F1 .  .  .  .  LM 
Leave the Hydrogen Generator on floor three, but bring the Hydrogen-compatible Microchip back down with you so you can still use the elevator:

F4 .  .  .  .  .  
F3 .  HG .  LG .  
F2 E  .  HM .  .  
F1 .  .  .  .  LM 
At the first floor, grab the Lithium-compatible Microchip, which is safe because Microchips don't affect each other:

F4 .  .  .  .  .  
F3 .  HG .  LG .  
F2 .  .  .  .  .  
F1 E  .  HM .  LM 
Bring both Microchips up one floor, where there is nothing to fry them:

F4 .  .  .  .  .  
F3 .  HG .  LG .  
F2 E  .  HM .  LM 
F1 .  .  .  .  .  
Bring both Microchips up again to floor three, where they can be temporarily connected to their corresponding generators while the elevator recharges, preventing either of them from being fried:

F4 .  .  .  .  .  
F3 E  HG HM LG LM 
F2 .  .  .  .  .  
F1 .  .  .  .  .  
Bring both Microchips to the fourth floor:

F4 E  .  HM .  LM 
F3 .  HG .  LG .  
F2 .  .  .  .  .  
F1 .  .  .  .  .  
Leave the Lithium-compatible microchip on the fourth floor, but bring the Hydrogen-compatible one so you can still use the elevator; this is safe because although the Lithium Generator is on the destination floor, you can connect Hydrogen-compatible microchip to the Hydrogen Generator there:

F4 .  .  .  .  LM 
F3 E  HG HM LG .  
F2 .  .  .  .  .  
F1 .  .  .  .  .  
Bring both Generators up to the fourth floor, which is safe because you can connect the Lithium-compatible Microchip to the Lithium Generator upon arrival:

F4 E  HG .  LG LM 
F3 .  .  HM .  .  
F2 .  .  .  .  .  
F1 .  .  .  .  .  
Bring the Lithium Microchip with you to the third floor so you can use the elevator:

F4 .  HG .  LG .  
F3 E  .  HM .  LM 
F2 .  .  .  .  .  
F1 .  .  .  .  .  
Bring both Microchips to the fourth floor:

F4 E  HG HM LG LM 
F3 .  .  .  .  .  
F2 .  .  .  .  .  
F1 .  .  .  .  .  
In this arrangement, it takes 11 steps to collect all of the objects at the fourth floor for assembly. (Each elevator stop counts as one step, even if nothing is added to or removed from it.)

In your situation, what is the minimum number of steps required to bring all of the objects to the fourth floor?

In [1]:
import re
import numpy as np
from itertools import combinations, chain

RE_MICROCHIP = re.compile("a ([a-z]+)\-compatible microchip")
RE_GENERATOR = re.compile("a ([a-z]+) generator")
FLOOR = lambda s: next(iter([idx for idx, val in enumerate(["first", "second", "third", "fourth"]) if val in s]), None)
ELEMENT = lambda e: e[:2].upper()


def build_status(instructions):
    floors = [""] * 4
    for ins in instructions:
        floor = FLOOR(ins)
        generators = {ELEMENT(e) for e in RE_GENERATOR.findall(ins)}
        microchips = {ELEMENT(e) for e in RE_MICROCHIP.findall(ins)}
        floors[floor] = (generators, microchips)
    return floors


def valid_floor(generators, microchips):
    return len(generators) == 0 or len(microchips) == 0 or np.all([m in generators for m in microchips])


def possible_movements(orig, dest, status):
    movements = []

    # Impossible floor discard
    if dest < 0 or dest >= len(status):
        return movements

    # Generators and micros at origin and destination
    orig_gen, orig_micro = status[orig]
    dest_gen, dest_micro = status[dest]

    # Move paired generator+microchip
    movements += [({g}, {g}) for g in orig_gen if g in orig_micro and valid_floor(dest_gen | set(g), dest_micro | set(g)) and valid_floor(orig_gen - {g}, orig_micro - {g})]

    # Move generators
    movements += [(set(pair), set()) for pair in chain(combinations(orig_gen, 2), combinations(orig_gen, 1)) if valid_floor(dest_gen | set(pair), dest_micro) and valid_floor(orig_gen - set(pair), orig_micro)]

    # Move microchips
    movements += [(set(), set(pair)) for pair in chain(combinations(orig_micro, 2), combinations(orig_micro, 1)) if valid_floor(dest_gen, dest_micro | set(pair)) and valid_floor(orig_gen, orig_gen - set(pair))]

    #return movements
    return sorted(movements, key=lambda v: sum(map(len, v)), reverse=(orig < dest))


def apply_movements(orig, dest, movement, status):

    # Create a copy of the current status
    new_status = [(set(g), set(m)) for g, m in status]

    # Move generators and microchips
    for i, elements in enumerate(movement):
        for e in elements:
            new_status[orig][i].remove(e)
            new_status[dest][i].add(e)

    return new_status


def compute_possible_status(orig, dest, status):
    return [apply_movements(orig, dest, m, status) for m in possible_movements(orig, dest, status)]


def print_status(elevator, status):
    print("----------------------")
    for f in range(3, -1, -1):
        e = 'E' if elevator == f else '.'
        g = ' '.join(["{}G".format(e) for e in status[f][0]] + ["{}M".format(e) for e in status[f][1]])
        print("F{} {} {}".format(f+1, e, g))
    print("----------------------")
    
    
def encode_status(elevator, status):
    #return "{}{}".format(elevator, "".join(["{}g{}m".format("".join(g), "".join(m)) for g, m in status]))
    return "{}{}".format(elevator, "".join(["{}g{}m".format("".join(["." for _ in g]), "".join(["." for _ in m])) for g, m in status]))

def move(status):

    visited = {encode_status(0, status)}
    possible_next_status = [([status], 1, s) for s in compute_possible_status(0, 1, status)]

    while len(possible_next_status) > 0:
        thread_status, elevator, next_status = possible_next_status.pop(0)
        
        next_status_encoded = encode_status(elevator, next_status)
        if next_status_encoded in visited:
            #print(next_status_encoded)
            #print(visited)
            #return None
            continue

        # Check if everything it's at the fourth floor
        if elevator == 3:
            if sum([sum([len(i) for i in next_status[f]]) for f in range(3)]) == 0:
                return thread_status + [next_status]
        
        possible_next_status += [(thread_status + [next_status], elevator+1, s) for s in compute_possible_status(elevator, elevator+1, next_status)]
        possible_next_status += [(thread_status + [next_status], elevator-1, s) for s in compute_possible_status(elevator, elevator-1, next_status)]
        
        visited.add(next_status_encoded)

    return None

In [2]:
example = [
    "The first floor contains a hydrogen-compatible microchip and a lithium-compatible microchip.", 
    "The second floor contains a hydrogen generator.",
    "The third floor contains a lithium generator.",
    "The fourth floor contains nothing relevant."
]

In [3]:
%%time
len(move(build_status(example))) - 1


CPU times: user 36 ms, sys: 0 ns, total: 36 ms
Wall time: 37.3 ms
Out[3]:
11

In [4]:
%%time
with open('inputs/day11.txt', 'rt') as fd:
    print(len(move(build_status(fd))) - 1)


33
CPU times: user 612 ms, sys: 4 ms, total: 616 ms
Wall time: 616 ms
--- Part Two ---

You step into the cleanroom separating the lobby from the isolated area and put on the hazmat suit.

Upon entering the isolated containment area, however, you notice some extra parts on the first floor that weren't listed on the record outside:

An elerium generator.
An elerium-compatible microchip.
A dilithium generator.
A dilithium-compatible microchip.
These work just like the other generators and microchips. You'll have to get them up to assembly as well.

What is the minimum number of steps required to bring all of the objects, including these four new ones, to the fourth floor?

In [5]:
%%time
with open('inputs/day11.txt', 'rt') as fd:
    status = build_status(fd)
    status[0][0].add("EL")
    status[0][0].add("DI")
    status[0][1].add("EL")
    status[0][1].add("DI")    
    print(len(move(status)) - 1)


57
CPU times: user 3.44 s, sys: 0 ns, total: 3.44 s
Wall time: 3.44 s

In [ ]: